package com.yingside.collection.stack;

public class MyStack<E> implements IStack<E> {

    private Object [] objs;
    private int max;
    private int top;

    public MyStack() {
        this(10);
    }

    public MyStack(int initialSize) {
        if(initialSize < 0){
            initialSize = 10;
        }
        this.objs = new Object[initialSize];
        this.max = initialSize;
        this.top = -1;
    }

    @Override
    public void push(E e) {
        if(this.isMax()){
            throw new MyStackException("栈已经满了！");
        }
        this.top ++;
        objs[top] = e;
    }

    @Override
    public E pop() {
        if(this.isEmpty()){
            throw new MyStackException("栈已经空了");
        }
        E e = (E)objs[this.top];
        this.top --;
        return e;
    }

    @Override
    public boolean isEmpty() {
        return this.top == -1;
    }

    @Override
    public boolean isMax() {
        return this.top==this.max - 1;
    }

    @Override
    public E peek() {
        E e = (E)this.objs[this.top];
        return e;
    }

    @Override
    public E indexOf(int index) {
        if(index < 0 || index > top){
            throw new MyStackException("栈下标越界！");
        }
        E e = (E)this.objs[index];
        return e;
    }

    @Override
    public void display() {
        for (int i = 0; i <= top; i++) {
            System.out.println("objs = " + objs[i]);
        }

    }

    @Override
    public int size() {
        return this.top+1;
    }
}
